package nicg.st.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import net.sf.json.JSONObject;

public class SendHttp {

	@SuppressWarnings("unchecked")
	public static Map<String, Object> sendPost(String sendMsg, String sendUrl) {
		HttpPost httpPost = new HttpPost(sendUrl);
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
		StringEntity entity;
		Map<String, Object> mres = new HashMap<String, Object>();
		try {
			entity = new StringEntity(sendMsg, "UTF-8"); // 解决参数中文乱码问题
			entity.setContentEncoding("UTF-8"); // 设置编码格式
			entity.setContentType("application/json");
			httpPost.setEntity(entity);
			// 发起请求
			HttpResponse httpResponse = closeableHttpClient.execute(httpPost);
			// 请求结束，返回结果。并解析json。
			String resData = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
			mres = (Map<String, Object>) JSONObject.toBean(JSONObject.fromObject(resData), Map.class);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != closeableHttpClient) {
				try {
					closeableHttpClient.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return mres;
	}

	public static String sendPostReturnString(String sendMsg, String sendUrl) {
		HttpPost httpPost = new HttpPost(sendUrl);
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
		StringEntity entity;
		String resData = new String();
		try {
			entity = new StringEntity(sendMsg, "UTF-8"); // 解决参数中文乱码问题
			entity.setContentEncoding("UTF-8"); // 设置编码格式
			entity.setContentType("application/json");
			httpPost.setEntity(entity);
			// 发起请求
			HttpResponse httpResponse = closeableHttpClient.execute(httpPost);
			// 请求结束，返回结果。并解析json。
			resData = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != closeableHttpClient) {
				try {
					closeableHttpClient.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return resData;
	}
}
